package com.syezon.wifikey.wifi;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.bumptech.glide.Glide;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.syezon.android.base.utils.AppUtils;
import com.syezon.android.base.utils.ToastUtils;
import com.syezon.wifikey.ad.AdPositionEnum;
import com.syezon.wifikey.ad.AdUtils;
import com.syezon.wifikey.ad.BannerAd;
import com.syezon.wifikey.ad.CommonAdCallBack;
import com.syezon.wifikey.ad.CommonAdConfig;
import com.syezon.wifikey.ad.CommonAdViewModel;
import com.syezon.wifikey.ad.CommonNewAdCallBack;
import com.syezon.wifikey.ad.ConfigService;
import com.syezon.wifikey.ad.FullVideoAd;
import com.syezon.wifikey.ad.NewBannerAd;
import com.syezon.wifikey.ad.SDKReportHelper;
import com.syezon.wifikey.ad.VideoAd;
import com.syezon.wifikey.analysis.AnalysisHelper;
import com.syezon.wifikey.base.BaseFragment;
import com.syezon.wifikey.R;
import com.syezon.wifikey.base.PermissionCallBack;
import com.syezon.wifikey.cengwang.CengwangTestActivity;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.GDTConfig;
import com.syezon.wifikey.config.TTAdManagerHolder;
import com.syezon.wifikey.enhance.EnhanceActivity;
import com.syezon.wifikey.home.MainActivity;
import com.syezon.wifikey.home.info.WifiListInfo;
import com.syezon.wifikey.imageloader.ImageLoader;
import com.syezon.wifikey.safe.SafeCheckActivity;
import com.syezon.wifikey.speed.SpeedTestActivity;
import com.syezon.wifikey.speedup.SpeedUpConfig;
import com.syezon.wifikey.speedup.SpeedUpHelper;
import com.syezon.wifikey.utils.StatusBarUtil;
import com.syezon.wifikey.utils.Utils;
import com.syezon.wifikey.utils.WifiUtil;
import com.syezon.wifikey.wifi.adapter.WifiListAdapter;
import com.syezon.wifikey.wifi.dialog.ConnectingDialog;
import com.syezon.wifikey.wifi.dialog.EnterPwdDialog;
import com.syezon.wifikey.wifi.dialog.GpsGuideDialog;
import com.syezon.wifikey.wifi.dialog.WifiInfoDialog;
import com.syezon.wifikey.wifi.info.WifiConnectionInfo;
import com.syezon.wifikey.wifi.info.WifiInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WiFiFragment extends BaseFragment implements WifiListAdapter.ItemClickListener, FullVideoAd.OnFullVideoAdLoadFailedListener, VideoAd.OnVideoAdLoadFailedListener {

    private static final String TAG = WiFiFragment.class.getSimpleName();

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    @BindView(R.id.appbarlayout)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.collapsingToolbar)
    CollapsingToolbarLayout mCollapsingToolBar;
    @BindView(R.id.ll_test)
    LinearLayout mLlTest;
    @BindView(R.id.ll_top)
    LinearLayout mLlContent;

    @BindView(R.id.tv_connect_state)
    TextView mTvConnectState;
    @BindView(R.id.tv_ssid)
    TextView mTvSSid;
    @BindView(R.id.iv_wifi_signal)
    ImageView mIvWifiSignal;

    @BindView(R.id.nv_without_data_layout)
    NestedScrollView mNsNoWifi;
    @BindView(R.id.nv_wifi_list)
    NestedScrollView mNsWifiList;
    @BindView(R.id.rv_wifi)
    RecyclerView mRvWifiList;
    @BindView(R.id.iv_wifi_state)
    ImageView mIvWifiState;
    @BindView(R.id.tv_empty_desc)
    TextView mTvWifiEmptyDes;
    @BindView(R.id.tv_empty_desc2)
    TextView mTvWifiEmptySubDes;

    //speedup
    @BindView(R.id.rl_speed_up)
    RelativeLayout mRlSpeedUp;
    @BindView(R.id.iv_speed_up_rocket_indicator)
    ImageView mIvSpeedUpIndicator;
    @BindView(R.id.tv_speed_score)
    TextView mTvSpeedScore;
    @BindView(R.id.tv_speed_up)
    TextView mTvSpeedUp;
    private int mWiFiSpeedUpScore;
    private int mWiFiSpeedUpAddPercent;

    //WifiOps
    @BindView(R.id.ll_wifi_op)
    LinearLayout mLlWifiOp;


    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.tv_open_wifi)
    TextView mTvOpenWifi;

    @BindView(R.id.iv_float_ad)
    ImageView mIvFloatWifiTop;
    private CommonAdConfig mTopFloatAdConfig;
    private CommonAdViewModel mTopFloatAdViewModel;
    private AdInfo nextAdSourceTop;

    @BindView(R.id.iv_float_ad_wifi_bottom)
    ImageView mIvFloatWifiBottom;

    private CommonAdConfig mBtmFloatAdConfig;
    private CommonAdViewModel mBtmFloatAdViewModel;
    private AdInfo nextAdSourceBtm;

    private WifiListAdapter mWifiListAdapter;
    private WifiInfoDialog mWifiInfoDialog;
    private ConnectingDialog mConnectionDialog;
    private GpsGuideDialog mGpsGuideDialog;

    private String mCurrentSsid;

    private boolean mConnectedWifi;
    private FullVideoAd mFullVideoAd;
    private VideoAd videoAd;

    private CommonAdConfig mBannerAdConfig;
    private CommonAdViewModel mBannerAdViewModel;

    private CommonAdConfig mWifiAdConfig;
    private CommonAdViewModel mWifiViewModel;
    private NewBannerAd bannerAd;
    private boolean isLoadedBanner = false;

    private AnimationSet animationSet;
    private WiFiObserver wiFiObserver = new WiFiObserver() {
        @Override
        public void onWifiStateChange(boolean isOpen) {
            if (isOpen) {
                showNormalView();
            } else {
                showWifiCloseView();
            }
        }

        @Override
        public void onGpsStateChange(boolean isGpsOpen) {
            if (isGpsOpen) {
                showNormalView();
                if (mGpsGuideDialog != null && mGpsGuideDialog.isShowing()) {
                    mGpsGuideDialog.dismiss();
                }
            }
        }

        @Override
        public void onWiFiListChange(List<WifiInfo> wifiInfos) {

        }

        @Override
        public void onWiFiListInfoChange(List<WifiListInfo> wifiListInfos) {
            showNormalView();
            if (wifiListInfos.size() > 0) {
                mNsNoWifi.setVisibility(View.GONE);
                mNsWifiList.setVisibility(View.VISIBLE);
                mRvWifiList.setVisibility(View.VISIBLE);
                mWifiListAdapter.setData(wifiListInfos);
            } else {
                showNoWifiView();
            }
        }

        @Override
        public void onLocationPermissionDeny() {
            showNoLocationPermissionView();
        }

        @Override
        public void onGpsPermissionDeny() {
            showNoGpsPermissionView();
            showGpsGuideDialog();
        }
    };

    private TTAdNative mTTAdNative;
    @BindView(R.id.flCsjContainer)
    FrameLayout mFlCsjContainer;
    @BindView(R.id.iv_banner)
    ImageView ivBanner;
    private static final int ANIMATION = 11;
    private static final int ANIMATION2 = 12;
    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ANIMATION:
                    if (mIvFloatWifiTop.isShown() && animationSet != null) {
                        mIvFloatWifiTop.clearAnimation();
                        mIvFloatWifiTop.startAnimation(animationSet);
                    }
                    mHandler.sendEmptyMessageDelayed(ANIMATION, 7000);
                    break;
                case ANIMATION2:
                    if (mIvFloatWifiBottom.isShown() && animationSet != null) {
                        mIvFloatWifiBottom.clearAnimation();
                        mIvFloatWifiBottom.startAnimation(animationSet);
                    }
                    mHandler.sendEmptyMessageDelayed(ANIMATION2, 7000);
                    break;
            }
        }
    };
    private TTNativeExpressAd mTTNativateExpressAd;
    private AdInfo nextAdSourceBanner;
    public WiFiFragment() {
    }

    public static WiFiFragment newInstance() {
        WiFiFragment fragment = new WiFiFragment();
        return fragment;
    }

    public static WiFiFragment newInstance(String param1, String param2) {
        WiFiFragment fragment = new WiFiFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @OnClick({
            R.id.tv_open_wifi
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_open_wifi:
                if (!WifiSupport.isOpenWifi()) {
                    WifiSupport.openWifi();
                }
                break;
        }
    }

    @OnClick({R.id.tv_speed_up, R.id.ll_check_safe, R.id.ll_signal_enhance, R.id.ll_speed_test, R.id.ll_online_device})
    public void onCheckViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_speed_up:
                SpeedUpHelper.speedUp(mContext, WifiUtil.getWifiSSID(), mWiFiSpeedUpScore, mWiFiSpeedUpAddPercent);
                break;
            case R.id.ll_check_safe:
                if (!TextUtils.isEmpty(mCurrentSsid)) {
                    Bundle bundle = new Bundle();
                    bundle.putString(SafeCheckActivity.ARG_SSID, mCurrentSsid);
                    readyGo(SafeCheckActivity.class, bundle);
                }
                break;
            case R.id.ll_signal_enhance:
                if (!TextUtils.isEmpty(mCurrentSsid)) {
                    Bundle bundle = new Bundle();
                    bundle.putString(EnhanceActivity.ARG_SSID, mCurrentSsid);
                    readyGo(EnhanceActivity.class, bundle);
                }
                break;
            case R.id.ll_speed_test:
                if (!TextUtils.isEmpty(mCurrentSsid)) {
                    Bundle speedTestBundle = new Bundle();
                    speedTestBundle.putString(SpeedTestActivity.ARG_SSID, mCurrentSsid);
                    readyGo(SpeedTestActivity.class, speedTestBundle);
                }
                break;
            case R.id.ll_online_device:
                readyGo(CengwangTestActivity.class);
                break;
        }
    }

    @Override
    protected void initViewsAndEvents() {

        mRvWifiList.setLayoutManager(new LinearLayoutManager(getContext()));
        StatusBarUtil.setPadding(getContext(), mAppBarLayout);
        StatusBarUtil.setPadding(getContext(), mLlContent);
        StatusBarUtil.setMargin(getContext(), mIvFloatWifiTop);
        mLlContent.setVisibility(View.GONE);
        mIvSpeedUpIndicator.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.app_speed_up_checking));
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int abs = Math.abs(verticalOffset);
                if (abs > SizeUtils.dp2px(55)) {
                    mLlTest.setVisibility(View.INVISIBLE);
                    mLlContent.setVisibility(View.VISIBLE);
                } else {
                    double currentAlpha = Math.abs(verticalOffset) * 1.0 / SizeUtils.dp2px(55) * 1.0;
                    mLlTest.setAlpha((float) (1 - currentAlpha));
                    mLlTest.setVisibility(View.VISIBLE);
                    mLlContent.setVisibility(View.GONE);
                }
            }
        });
        initAnimation();
        mWifiListAdapter = new WifiListAdapter(getContext());
        mWifiListAdapter.setItemClickListener(this);
        mRvWifiList.setAdapter(mWifiListAdapter);
        setConnectInfo(WifiConnectService.getInstance().getCurrentConnectionInfo());
        WifiListUtils.getInstance().registerWifiObserver(wiFiObserver);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh();
                WifiListUtils.getInstance().updateWifiList();
            }
        });
        getWifiList();
        WifiConnectService.getInstance().getWifiConnectionInfoMutableLiveData().observe(this, new Observer<WifiConnectionInfo>() {
            @Override
            public void onChanged(@Nullable WifiConnectionInfo wifiConnectionInfo) {
                setConnectInfo(wifiConnectionInfo);
            }
        });
        //initTTAd();
        getAds();
    }



    private void getAds() {
        mTopFloatAdConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.FLOAT_HOME_TOP);

        mTopFloatAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.FLOAT_HOME_TOP.getUmengEventId(), CommonAdViewModel.class);
        mTopFloatAdViewModel.setAdPositionEnum(AdPositionEnum.FLOAT_HOME_TOP);
        mTopFloatAdViewModel.getAdLiveData().observe(this, new Observer<List<com.hodanet.appadvplatclient.ad.AdInfo>>() {
            @Override
            public void onChanged(@Nullable List<com.hodanet.appadvplatclient.ad.AdInfo> adInfos) {
                mTopFloatAdConfig.setAdList(adInfos);
                showTopFloatAd();
                mHandler.sendEmptyMessageDelayed(ANIMATION, 2000);
            }
        });
        mBtmFloatAdConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.FLOAT_HOME_BOTTOM);
        mBtmFloatAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.FLOAT_HOME_BOTTOM.getUmengEventId(), CommonAdViewModel.class);
        mBtmFloatAdViewModel.setAdPositionEnum(AdPositionEnum.FLOAT_HOME_BOTTOM);
        mBtmFloatAdViewModel.getAdLiveData().observe(this, new Observer<List<com.hodanet.appadvplatclient.ad.AdInfo>>() {
            @Override
            public void onChanged(@Nullable List<com.hodanet.appadvplatclient.ad.AdInfo> adInfos) {
                mBtmFloatAdConfig.setAdList(adInfos);
                showBottomFloatAd();
                mHandler.sendEmptyMessageDelayed(ANIMATION2, 2000);
            }
        });
        mWifiAdConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.WIFI_LIST_AD);
        mWifiViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.WIFI_LIST_AD.getUmengEventId(), CommonAdViewModel.class);
        mWifiViewModel.setAdPositionEnum(AdPositionEnum.WIFI_LIST_AD);
        mWifiViewModel.getAdLiveData().observe(this, new Observer<List<com.hodanet.appadvplatclient.ad.AdInfo>>() {
            @Override
            public void onChanged(@Nullable List<com.hodanet.appadvplatclient.ad.AdInfo> adInfos) {
                mWifiAdConfig.setAdList(adInfos);
                showWifiAd();
            }
        });
        mBannerAdConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.BOX_AD_1.getUmengEventId());
        bannerAd = new NewBannerAd(getActivity(), mFlCsjContainer,CommonAdViewModel.KEY_PREFIX + AdPositionEnum.BOX_AD_1.getUmengEventId(),TTAdManagerHolder.BANNER, GDTConfig.BANNER_AD);
        mBannerAdViewModel = ViewModelProviders.of(this).get(CommonAdViewModel.KEY_PREFIX + AdPositionEnum.BOX_AD_1.getUmengEventId(), CommonAdViewModel.class);
        mBannerAdViewModel.setAdPositionEnum(AdPositionEnum.BOX_AD_1);
        mBannerAdViewModel.getAdLiveData().observe(this, new Observer<List<AdInfo>>() {
            @Override
            public void onChanged(@Nullable List<AdInfo> adInfos) {
//                mBannerAdConfig.setAdList(adInfos);
//                bannerAd.setCommonNewAdCallBack(WiFiFragment.this);
//                bannerAd.setCommonAdCallBack(WiFiFragment.this);
                bannerAd.getBannerAdConfig().setAdList(adInfos);
                isLoadedBanner = true;
                loadBanner();
            }
        });
    }

    private void showWifiAd() {
        AdInfo nextAdSource = mWifiAdConfig.getNextAdSource();
        if (nextAdSource != null) {
            ReportAgent.reportAdvExtShow(nextAdSource,ChannelConfig.getChannel(),AppUtils.getAppVersionCode());
            mWifiListAdapter.setAdInfo(nextAdSource);
            mWifiAdConfig.saveLastShowAd(nextAdSource);
        }
    }

    private void loadBanner() {
        bannerAd.loadBannerAdByAdInfo();
    }
    @Override
    public void onResume() {
        super.onResume();
        //switchAd(true);
        if (mConnectedWifi) {
            mWiFiSpeedUpScore = SpeedUpConfig.getCurrentScore(mCurrentSsid);
            mWiFiSpeedUpAddPercent = SpeedUpConfig.getCurrentAddPercent(mCurrentSsid);
            mTvSpeedScore.setText("网速评分: " + mWiFiSpeedUpScore + "分");
            SpanUtils.with(mTvSpeedUp).append("一键加速")
                    .append("+" + mWiFiSpeedUpAddPercent).setBold().append("%").setFontSize(11, true).create();
        }
        if (isAdded() && !isHidden()) {
            showTopFloatAd();
            showBottomFloatAd();
            loadBanner();
            showWifiAd();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            showTopFloatAd();
            showBottomFloatAd();
            loadBanner();
            showWifiAd();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        WifiListUtils.getInstance().removeWifiObserver(wiFiObserver);
        if (mTTNativateExpressAd != null) {
            mTTNativateExpressAd.destroy();
        }
        if (bannerAd != null) {
            bannerAd.destroy();
        }
    }

    public void switchAd(boolean isResume) {
        try {
            boolean switchAd = true;
            if (isResume && isHidden()) {
                switchAd = false;
            }
            if (switchAd) {
//                showTopFloatAd();
//                showBottomFloatAd();
            }
        } catch (Exception e) {

        }
    }

    public void showBottomFloatAd() {
        nextAdSourceBtm = mBtmFloatAdConfig.getNextAdSource();
        if (nextAdSourceBtm != null) {
            mIvFloatWifiBottom.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(WiFiFragment.this, nextAdSourceBtm.getPic(), mIvFloatWifiBottom);
            AnalysisHelper.onAdEvent(AdPositionEnum.FLOAT_HOME_BOTTOM, AnalysisHelper.EVENT_EXT_SHOW, nextAdSourceBtm.getId() + "");
            ReportAgent.reportAdvExtShow(nextAdSourceBtm, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            mIvFloatWifiBottom.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    handleFloatAdClick(nextAdSourceBtm,AdPositionEnum.FLOAT_HOME_BOTTOM);
                }
            });
            mBtmFloatAdConfig.saveLastShowAd(nextAdSourceBtm);
        } else {
            mIvFloatWifiBottom.setVisibility(View.GONE);
        }
    }

    public void showTopFloatAd() {
        nextAdSourceTop = mTopFloatAdConfig.getNextAdSource();
        if (nextAdSourceTop != null) {
            mIvFloatWifiTop.setVisibility(View.VISIBLE);
            ImageLoader.getInstance().displayImage(getContext(), nextAdSourceTop.getPic(), mIvFloatWifiTop);
            AnalysisHelper.onAdEvent(AdPositionEnum.FLOAT_HOME_TOP, AnalysisHelper.EVENT_EXT_SHOW, nextAdSourceTop.getId() + "");
            ReportAgent.reportAdvExtShow(nextAdSourceTop, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            mIvFloatWifiTop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    handleFloatAdClick(nextAdSourceTop, AdPositionEnum.FLOAT_HOME_TOP);
                }
            });
            mTopFloatAdConfig.saveLastShowAd(nextAdSourceTop);
        } else {
            mIvFloatWifiTop.setVisibility(View.GONE);
        }
    }

    private void handleFloatAdClick(AdInfo nextAdSource, AdPositionEnum adPositionEnum) {
        if (nextAdSource.getType() == AdInfo.AD_TYPE_CSJ_FULL_VIDEO) {
            loadFullVideoAd(nextAdSource);
            ReportAgent.reportAdvClick(nextAdSource, ChannelConfig.getChannel(), com.blankj.utilcode.util.AppUtils.getAppVersionCode());
        } else if (nextAdSource.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG || nextAdSource.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
            videoAd = new VideoAd(getActivity());
            videoAd.setOnVideoAdLoadFailedListener(this);
            videoAd.loadVideoAd(nextAdSource);
            ReportAgent.reportAdvClick(nextAdSource, ChannelConfig.getChannel(), com.blankj.utilcode.util.AppUtils.getAppVersionCode());
        } else {
            AdUtils.adClicked(getContext(), nextAdSource, adPositionEnum);
        }
        //showBottomFloat();
    }

    private void loadFullVideoAd(AdInfo posId) {
        if (mFullVideoAd == null) {
            mFullVideoAd = new FullVideoAd();
            mFullVideoAd.setOnFullVideoAdLoadFailedListener(this);
        }
        mFullVideoAd.loadAd(getActivity(), posId);
    }

    private void setConnectInfo(final WifiConnectionInfo wifiConnectionInfo) {
        if (wifiConnectionInfo.isConnected()) {
            mConnectedWifi = true;
            mLlWifiOp.setVisibility(View.VISIBLE);
            mCurrentSsid = wifiConnectionInfo.getSsid();
            mTvSSid.setText(mCurrentSsid);
            mTvConnectState.setText("已连接");
            mRlSpeedUp.setVisibility(View.VISIBLE);
            mLlWifiOp.setVisibility(View.VISIBLE);
            mIvWifiSignal.setVisibility(View.VISIBLE);
            setWiFiSignal();
            mWiFiSpeedUpScore = SpeedUpConfig.getCurrentScore(mCurrentSsid);
            mWiFiSpeedUpAddPercent = SpeedUpConfig.getCurrentAddPercent(mCurrentSsid);
            if (wifiConnectionInfo.isGpsDeny()) {
                mTvConnectState.setText("当前使用WiFi网络");
                mTvSSid.setText("请打开定位权限获取更多免费WiFi");
                mLlWifiOp.setVisibility(View.GONE);
                mRlSpeedUp.setVisibility(View.GONE);
                mIvWifiSignal.setVisibility(View.GONE);
            }
        } else {
            mConnectedWifi = false;
            mCurrentSsid = null;
            mLlWifiOp.setVisibility(View.GONE);
            mTvSSid.setText("请先连接WiFi网络");
            mTvConnectState.setText("当前未连接WiFi网络");
            mRlSpeedUp.setVisibility(View.GONE);
            mLlWifiOp.setVisibility(View.GONE);
            mIvWifiSignal.setVisibility(View.GONE);
        }
    }

    private void setWiFiSignal() {
        try {
            WifiManager mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            android.net.wifi.WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
            if (wifiInfo != null) {
                int rssi = wifiInfo.getRssi();//获取wifi信号强度
                if (rssi > -50 && rssi < 0) {//最强
                    mIvWifiSignal.setImageResource(R.drawable.app_wifi_level_4);
                } else if (rssi > -70 && rssi < -50) {//较强
                    mIvWifiSignal.setImageResource(R.drawable.app_wifi_level_3);
                } else if (rssi > -80 && rssi < -70) {//较弱
                    mIvWifiSignal.setImageResource(R.drawable.app_wifi_level_2);
                } else if (rssi > -100 && rssi < -80) {//微弱
                    mIvWifiSignal.setImageResource(R.drawable.app_wifi_level_1);
                }
            } else {
                mIvWifiSignal.setVisibility(View.GONE);
            }
        } catch (Exception e) {

        }

    }

    private void showConnectiongDialog() {
        if (mConnectionDialog == null) {
            mConnectionDialog = new ConnectingDialog(getContext(), R.style.Dialog);
        }
        if (!mConnectionDialog.isShowing()) {
            mConnectionDialog.show();
        }
    }
    private void initAnimation() {
        //由小变大
        Animation scaleAnim = new ScaleAnimation(0.8f, 1.1f, 0.8f, 1.1f);
        //从左向右
        Animation rotateAnim = new RotateAnimation(-10f, 10f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        scaleAnim.setDuration(1000);
        rotateAnim.setDuration(1000 / 10);
        rotateAnim.setRepeatMode(Animation.REVERSE);
        rotateAnim.setRepeatCount(30);

        animationSet = new AnimationSet(false);
        animationSet.addAnimation(scaleAnim);
        animationSet.addAnimation(rotateAnim);
    }
    private void showGpsGuideDialog() {
        if (mGpsGuideDialog == null) {
            mGpsGuideDialog = new GpsGuideDialog(getContext(), R.style.Dialog);
        }
        if (!mGpsGuideDialog.isShowing()) {
            mGpsGuideDialog.show();
        }
    }

    private void dismissConnectiongDialog() {
        if (mConnectionDialog != null && mConnectionDialog.isShowing()) {
            mConnectionDialog.dismiss();
        }
    }

    private void getWifiList() {
        requestPermission(new PermissionCallBack() {
            @Override
            public void onResult(boolean isGrant, String... permission) {
                WifiListUtils.getInstance().updateWifiList();
            }
        }, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION);
    }

    /**
     * 没有可用WiFi视图
     */
    private void showNoWifiView() {
        updateWifiState();
        mNsWifiList.setVisibility(View.GONE);
        mRvWifiList.setVisibility(View.GONE);
        mNsNoWifi.setVisibility(View.VISIBLE);
        mIvWifiState.setImageResource(R.drawable.app_wifi_close_state);
        mTvWifiEmptyDes.setText(getString(R.string.wifi_tip_no_wifi_des));
        mTvOpenWifi.setVisibility(View.GONE);
        mTvWifiEmptySubDes.setText(getString(R.string.wifi_tip_no_wifi_sub_des));
    }

    /**
     * 正常视图
     */
    private void showNormalView() {
        updateWifiState();
        mNsWifiList.setVisibility(View.VISIBLE);
        mRvWifiList.setVisibility(View.VISIBLE);
        mNsNoWifi.setVisibility(View.GONE);
        mIvWifiState.setImageResource(R.drawable.app_wifi_close_state);
        mTvWifiEmptyDes.setText(getString(R.string.wifi_tip_gps_close_des));
        mTvWifiEmptySubDes.setText(getString(R.string.wifi_tip_gps_close_sub_des));
        mTvOpenWifi.setVisibility(View.GONE);
    }

    /**
     * 没有位置权限视图
     */
    private void showNoLocationPermissionView() {
        updateWifiState();
        mNsWifiList.setVisibility(View.GONE);
        mRvWifiList.setVisibility(View.GONE);
        mNsNoWifi.setVisibility(View.VISIBLE);
        mIvWifiState.setImageResource(R.drawable.app_wifi_location_deny);
        mTvSSid.setText("请打开定位权限获取更多免费WiFi");
        mTvWifiEmptyDes.setText(getString(R.string.wifi_tip_gps_close_des));
        mTvWifiEmptySubDes.setText(getString(R.string.wifi_tip_gps_close_sub_des));
        mTvOpenWifi.setText("开启定位权限，搜索热点");
        mTvOpenWifi.setVisibility(View.VISIBLE);
        mTvOpenWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                //设置去向意图
                Uri uri = Uri.fromParts("package", Utils.getApp().getPackageName(), null);
                intent.setData(uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().startActivity(intent);
            }
        });
    }

    /**
     * 没有Gps权限视图
     */
    private void showNoGpsPermissionView() {
        updateWifiState();
        mNsWifiList.setVisibility(View.GONE);
        mRvWifiList.setVisibility(View.GONE);
        mNsNoWifi.setVisibility(View.VISIBLE);
        mIvWifiState.setImageResource(R.drawable.app_wifi_location_deny);
        mTvWifiEmptyDes.setText(getString(R.string.wifi_tip_gps_close_des));
        mTvWifiEmptySubDes.setText(getString(R.string.wifi_tip_gps_close_sub_des));
        mTvOpenWifi.setText("开启GPS，搜索热点");
        mTvOpenWifi.setVisibility(View.VISIBLE);
        mTvOpenWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                getContext().startActivity(intent);
            }
        });
    }

    /**
     * WiFi关闭视图
     */
    private void showWifiCloseView() {
        updateWifiState();
        mNsWifiList.setVisibility(View.GONE);
        mRvWifiList.setVisibility(View.GONE);
        mNsNoWifi.setVisibility(View.VISIBLE);
        mTvWifiEmptyDes.setText(getString(R.string.wifi_tip_wifi_close_des));
        mTvWifiEmptySubDes.setText(getString(R.string.wifi_tip_wifi_close_sub_des));
        mIvWifiState.setImageResource(R.drawable.app_wifi_close_state);
        mTvOpenWifi.setText("开启WiFi，搜索热点");
        mTvOpenWifi.setVisibility(View.VISIBLE);
        mTvOpenWifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!WifiSupport.isOpenWifi()) {
                    WifiSupport.openWifi();
                }
            }
        });
    }

    private void updateWifiState() {
        WifiConnectionInfo currentConnectionInfo = WifiConnectService.getInstance().getCurrentConnectionInfo();
        setConnectInfo(currentConnectionInfo);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_wifi;
    }

    @Override
    public void onAdClick(AdInfo adInfo) {
        handleFloatAdClick(adInfo,AdPositionEnum.WIFI_LIST_AD);
    }

    @Override
    public void onWifiItemClick(WifiListInfo wifiListInfo) {
        int type = wifiListInfo.getType();
        if (type == WifiListInfo.TYPE_WIFI_INFO) {
            WifiInfo wifiInfo = wifiListInfo.getWifiInfo();
            if (wifiInfo.isConnected()) {
                ToastUtils.showShort("当前WiFi已连接!");
            } else {
                if (!wifiInfo.isAvailable()) {
                    ToastUtils.showShort("当前WiFi不可用!");
                } else {
                    if (wifiInfo.isConfig()) {
//                        ToastUtils.showShort("正在连接" + wifiInfo.getSsid());
//                        WifiConnectService.getInstance().connect(wifiInfo);
                        WiFiConnectDialog.connect(mContext, wifiInfo, new WiFiConnectDialog.ConnectCallBack() {
                            @Override
                            public void onSuccess() {
                                try {
                                    FragmentActivity activity = getActivity();
                                    if (activity != null && activity instanceof MainActivity) {
                                        ((MainActivity) activity).showNewsTab(null);
                                    }
                                } catch (Exception e) {

                                }

                            }

                            @Override
                            public void onFailed() {

                            }
                        });
                    } else {
                        EnterPwdDialog.enterPwd(mContext, wifiInfo, false);
                    }
                }
            }
//            if (mWifiInfoDialog == null) {
//                mWifiInfoDialog = new WifiInfoDialog(getContext(), R.style.Dialog);
//            }
//            mWifiInfoDialog.setWifiBean(wifiInfo);
//            mWifiInfoDialog.show();
        }
    }

    @Override
    public void onWifiMore(WifiListInfo wifiListInfo) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(WifiDetailActivity.ARG_WIFI_INFO, wifiListInfo.getWifiInfo());
        readyGo(WifiDetailActivity.class, bundle);
    }


    @Override
    public void onFullVideoLoadFailed() {
        if(videoAd == null){
            videoAd = new VideoAd(getActivity());
        }
        videoAd.loadVideoAd();
    }


    @Override
    public void onVideoAdLoadFailed() {
    }


}
